<template>
<el-container>
  <el-header class="no-flex" height="auto">
    <el-form
      label-width="70px"
      class="sys-filters"
      ref="formRef"
      inline
      :model="menuForm"
    >
      <el-form-item label="菜单名称" prop="name">
        <el-input placeholder="请输入菜单名称" clearable v-model="menuForm.name" style="width: 200px" />
      </el-form-item>

      <el-form-item label="状态" prop="enabled">
        <el-select
          style="width: 200px"
          placeholder="请选择岗位状态"
          clearable
          v-model="menuForm.enabled"
        >
          <el-option
            v-for="item in dicts.system_global_status"
            :key="item.v"
            :label="item.k"
            :value="item.v"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="菜单类型" prop="type">
        <el-select placeholder="请选择岗位状态" clearable v-model="menuForm.type" style="width: 200px">
          <el-option
            v-for="item in dicts.system_menu_type"
            :key="item.v"
            :label="item.k"
            :value="item.v"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"  icon="el-icon-search" @click="menuSearch">
          搜索
        </el-button>
        <el-button icon="el-icon-RefreshLeft" @click="menuReset">
          重置
        </el-button>
      </el-form-item>
      <el-form-item style="display: flex; margin-bottom: 0">
        <el-button type="primary" @click="menuAdd"  icon="el-icon-plus" v-auths="['*:*:*','system:menu:add']">新增</el-button>

      </el-form-item>
    </el-form>
  </el-header>
  <el-main class="nopadding">
    <el-table :data="menuList" row-key="id" stripe border height="auto">
      <el-table-column prop="name" label="菜单名称" align="left" width="200" />
      <el-table-column label="图标" align="center">
        <template #default="{ row }">
          <el-icon size='large' v-if="row.icon">
            <component :is="row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="perms" label="权限标识" align="center" width="180" >
        <template #default="{ row }">
          <el-link :underline="false" v-copy="row.perms" >{{ row.perms }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="菜单类型" align="center" width="100">
        <template #default="{row}">
          <template v-for="item in dicts.system_menu_type">
            <el-tag v-if="row.type == item.v">{{item.k}}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center" />
      <el-table-column label="显示状态" align="center" width="100">
        <template #default="{row}">
          <template v-for="item in dicts.system_global_visibility">
            <el-tag v-if="row.visible == item.v">{{item.k}}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="禁用状态" align="center" width="100">
        <template #default="{row}">
          <template v-for="item in dicts.system_global_status">
            <el-tag v-if="row.enabled == item.v">{{item.k}}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" :formatter="rendererDateTime" width="150" />
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="{ row }">
          <div class="sys-table-main-actions">
            <el-link
              v-auths="['*:*:*','system:menu:update']"
              icon="el-icon-edit"
              type="primary"
              :underline="false"
              style="margin-right: 4px"
              @click="menuUpdate(row)"
            >
              修改
            </el-link>
            <el-link
              v-auths="['*:*:*','system:menu:delete']"
              icon="el-icon-delete"
              type="danger"
              :underline="false"
              style="margin-left: 10px"
              @click="menuDelete(row.id)"
            >
              删除
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-main>

  <el-dialog
    v-model="show"
    :title="dialogForm.id ?'编辑菜单':'新增菜单'"
    width="800px"
    :append-to-body="true"
    :destroy-on-close="true"
    :before-close="onCancel"
  >
    <template #default>
      <el-form
        ref="dialogRef"
        :model="dialogForm"
        :rules="formRules"
        label-width="100px"
        class="form"
      >
        <el-form-item label="上级菜单" prop="parentMenu" >
          <el-tree-select
            style="width: 100%"
            v-model="dialogForm.parentId"
            :data="parentMenuTreeOptions.options"
            :props="parentMenuTreeOptions.props"
            :render-after-expand="false"
            :check-strictly="true"
            value-key="id"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="name" >
          <el-input placeholder="请输入菜单名称" v-model="dialogForm.name" />
        </el-form-item>

        <el-form-item label="显示排序" prop="sort" class="inline">
          <el-input-number v-model="dialogForm.sort" :min="1" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type" >
          <el-radio-group v-model="dialogForm.type" @change="cutChange">
            <el-radio :label="0" >目录</el-radio>
            <el-radio :label="1" >菜单</el-radio>
            <el-radio :label="2" >按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        目录-->
        <div v-if="dialogForm.type == 0">
<!--          菜单图标-->
          <el-form-item label="菜单图标" prop="meta.icon" class="inline">
            <sc-icon-select v-model="dialogForm.icon" clearable></sc-icon-select>
          </el-form-item>
          <!--            权限字符-->
          <el-form-item   prop="sort" class="inline" >
            <template #label>
              <el-tooltip
                effect="dark"
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPerm('system:user:list')`)"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">权限字符</span>
                </div>
              </el-tooltip>
            </template>

            <el-input v-model="dialogForm.perms" placeholder="请输入权限标识" />
          </el-form-item>
<!--          启用状态-->
          <el-form-item class="inline" >
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">状态</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.enabled">
              <el-radio
                v-for="item in dicts.system_global_status"
                :key="item.v"
                :label="dialogForm.enabled == item.v ? dialogForm.enabled : item.v "
              >
                {{ item.k }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
<!--          是否外联-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择是外链则路由地址需要以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否外链</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.outerChain">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
<!--          路由地址-->
          <el-form-item prop="path" class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="访问的路由地址，如：`/system/user`，如外网地址需内链访问则以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">路由地址</span>
                </div>
              </el-tooltip>
            </template>

            <el-input v-model="dialogForm.path" placeholder="请输入路由地址" />
          </el-form-item>
<!--            重定向地址-->
          <el-form-item prop="redirect" label="重定向地址" class="inline">
            <el-input v-model="dialogForm.redirect" placeholder="请输入重定向的地址" />
          </el-form-item>
<!--            是否显示-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否显示</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.visible">
              <el-radio
                v-for="item in dicts.system_global_visibility"
                :key="item.v"
                :label="dialogForm.visible == item.v ? dialogForm.visible : item.v "
              >
                {{ item.k }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
<!--        菜单-->
        <div v-if="dialogForm.type == 1">
          <!--          菜单图标-->
          <el-form-item label="菜单图标" prop="meta.icon">
            <sc-icon-select v-model="dialogForm.icon" clearable></sc-icon-select>
          </el-form-item>
          <!--          权限字符-->
          <el-form-item class="inline" prop="sort">
            <template #label>
              <el-tooltip
                effect="dark"
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPerm('system:user:list')`)"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">权限字符</span>
                </div>
              </el-tooltip>
            </template>

            <el-input v-model="dialogForm.perms" placeholder="请输入权限标识" />
          </el-form-item>
          <!--          是否外联-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择是外链则路由地址需要以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否外链</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.outerChain">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--          路由地址-->
          <el-form-item prop="path" class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="访问的路由地址，如：`/system/user`，如外网地址需内链访问则以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">路由地址</span>
                </div>
              </el-tooltip>
            </template>

            <el-input v-model="dialogForm.path" placeholder="请输入路由地址" />
          </el-form-item>
          <!--            重定向地址-->
          <el-form-item prop="redirect" label="重定向地址" class="inline">
            <el-input v-model="dialogForm.redirect" placeholder="请输入重定向的地址" />
          </el-form-item>
<!--          路由参数-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="访问路由的默认传递参数，如：`{id: 1, name: 'ry'}`"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">路由参数</span>
                </div>
              </el-tooltip>
            </template>

            <el-input v-model="dialogForm.query" placeholder="请输入路由参数" />
          </el-form-item>
<!--          是否缓存-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否缓存</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.cache">
              <el-radio
                v-for="item in dicts.system_global_cache"
                :key="item.v"
                :label="item.v"
              >
                {{ item.k }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
<!--          是否隐藏-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否显示</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.visible">
              <el-radio
                v-for="item in dicts.system_global_visibility"
                :key="item.v"
                :label="item.v"
              >
                {{ item.k }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!--          启用状态-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">状态</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.enabled">
              <el-radio
                v-for="item in dicts.system_global_status"
                :key="item.v"
                :label="item.v"
              >
                {{ item.k }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
<!--              组件路径-->
          <el-form-item label="组件路径" class="inline" prop="component">
            <el-input v-model="dialogForm.component" placeholder="请输入组件路径" />
          </el-form-item>
        </div>
        <!--        按钮-->
        <div v-if="dialogForm.type == 2" >
<!--          权限字符-->
          <el-form-item class="inline" prop="sort">
            <template #label>
              <el-tooltip
                effect="dark"
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPerm('system:user:list')`)"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">权限字符</span>
                </div>
              </el-tooltip>
            </template>

            <el-input v-model="dialogForm.perms" placeholder="请输入权限标识" />
          </el-form-item>
<!--            启用状态-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">状态</span>
                </div>
              </el-tooltip>
            </template>

            <el-radio-group v-model="dialogForm.enabled">
              <el-radio
                v-for="item in dicts.system_global_status"
                :key="item.v"
                :label="item.v"
              >
                {{ item.k }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
    </template>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</el-container>
</template>

<script>
import scIconSelect from "@renderer/components/scIconSelect/index.vue";

export default {
  name: "index",
  dicts: ['system_global_status','system_global_visibility','system_menu_type','system_global_cache'],
  components: {scIconSelect},
  data(){
    return{
      show:false,
      menuForm: {
        name: '',
        enabled: '',
        type: ''
      },
      menuList:[],
      current:1,
      size:9999,
      total:1000,
      dialogForm:{
        id:'',
        parentId: '-1',
        name: "",
        sort: 1,
        type: 0,    //菜单类型（0：目录；1：菜单；2：按钮）
        redirect:'',//重定向
        path:'',  //路由地址
        query: '',//路由参数
        component: '',//组件路径
        cache: '0',//是否缓存（0：缓存；1：不缓存）
        visible: '0',//显示状态（0：显示；1：隐藏）
        enabled: '1',//菜单状态（0：禁用；1：启用）
        perms: '',//权限标识
        icon: '',//图标
        remark: null,//备注
        outerChain:false //是否外联[若是以http/https开头的就是外联]
      },
      temp:{},
      formRules: {
        path: [
          { required: true, message: "路由地址为必填项", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (this.dialogForm.outerChain && !/^https?/.test(value)) {
                callback(new Error("外链地址必须是`http(s)`开头"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        name: [
          { required: true, message: "菜单名称为必填项", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "显示顺序为必填项", trigger: "blur" }
        ],
        perms:[
          { required: true, message: "权限标识为必填项", trigger: "blur" }
        ],
        component:[
          { required: true, message: "组件路径为必填项", trigger: "blur" }
        ]

      },
      parentMenuTreeOptions: {
        options: [],
        props: { children: "children", label: "name" }
      }
    }
  },
  created() {
    this.temp = this.$TOOL.object.clone(this.dialogForm)
    this.getMenuList()
  },
  methods:{
    // 菜单权限树
   async getMenuTree(){
      let { data } = await this.$API.system.menus.tree.get()
     this.parentMenuTreeOptions.options = [
       {
         id: "-1",
         name: "根目录",
         children: data
       }
     ]
    },

    //菜单列表
    async getMenuList(){
     let { data } =  await this.$API.system.menus.list.get({
        current:this.current,
        size:this.size,
        name: this.menuForm.name,
        enabled: this.menuForm.enabled,
        type: this.menuForm.type
      })
      this.current = data.current
      this.size = data.size
      this.total = data.total
      this.menuList = this.$TOOL.dataToTree(data.records)
    },
    menuSearch(){
      //搜索
      this.getMenuList()
    },
    menuReset(){
      //重置
      this.$refs.formRef.resetFields()
      this.menuForm = {}
      this.getMenuList()
    },
    menuAdd(){
      //+++
      this.show = true
      this.getMenuTree()
    },
   async menuUpdate(row){
      //修改
      this.show = true

      let { data } = await this.$API.system.menus.detail.get(row.id)
      this.dialogForm = data
      this.dialogForm.outerChain = false
      this.getMenuTree()
    },
    //取消
    onCancel(){
      this.show = false
      this.dialogForm = {}
      this.dialogForm.sort = 1
      this.dialogForm.type = 0
      this.dialogForm.visible = 0
      this.getMenuTree()
    },
    //确认
   async onSubmit(){
        try{
            await this.$refs.dialogRef.validate()
            if (this.dialogForm.id) {
                await this.$API.system.menus.update.post(this.dialogForm)
               } else {
                await this.$API.system.menus.add.post(this.dialogForm)
                }
              this.dialogForm = {} //清空
              this.$message.success('操作成功')
              this.getMenuList()
              this.show = false // 关闭弹窗
            } catch (error) {
              console.log(error)
              this.$message.error('操作失败')
            }
    },
    //点击切换
    cutChange(val){
      this.dialogForm = this.$TOOL.object.clone(this.temp)
      this.dialogForm.type = val
    },
    menuDelete(id){
      this.$confirm('此操作将删除此条数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$API.system.menus.delete.get(id)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.getMenuList()
      })
    },
    // 转换时间
    rendererDateTime(row, column, cellValue, index) {
      return this.$TOOL.dateFormat(cellValue)
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  :deep(.inline) {
    display: inline-flex;
    vertical-align: middle;
    width: 50%;
  }
  .center {
    display: inline-flex;
    align-items: center;
  }
  .l-4 {
    margin-left: 4px;
  }
}
</style>
